﻿using B.S.BaseData.ErrorCode;
using B.S.BaseData.Manage.Api.With.Apliaction.Command.ReportlossesModelCommand;
using B.S.Passport.ErrorCode;
using DAL;
using MediatR;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.BaseData.Manage.Api.With.Apliaction.CommandHandler.ReportlossesModelCommandHandler
{
    /// <summary>
    /// 报损修改
    /// </summary>
    public class ReportlossesUpdateModelCommandHandler : IRequestHandler<ReportlossesUpdateModelCommand, ApiReqult<object>>
    {
        private readonly DBHelper bHelper;
        private const int BatchSize = 100; // 每批处理的数据数量

        /// <summary>
        /// 连接数据库
        /// </summary>
        /// <param name="bHelper"></param>
        public ReportlossesUpdateModelCommandHandler(DBHelper bHelper)
        {
            this.bHelper = bHelper;
        }

        /// <summary>
        /// 报损修改
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<ApiReqult<object>> Handle(ReportlossesUpdateModelCommand request, CancellationToken cancellationToken)
        {
            var apiResult = new ApiReqult<object>();
            int totalRowsAffected = 0;

            // 前置检查：Id列表为null时直接返回错误
            if (request.Id == null)
            {
                apiResult.Code = ApiEnum.操作失败;
                apiResult.Msg = "更新操作需要提供有效的Id列表，Id参数不能为null";
                return apiResult;
            }

            if (request.Id.Count == 0)
            {
                apiResult.Code = ApiEnum.操作失败;
                apiResult.Msg = "更新操作需要提供有效的Id列表，Id列表不能为空";
                return apiResult;
            }

            for (int i = 0; i < request.Id.Count; i += BatchSize)
            {
                int endIndex = Math.Min(i + BatchSize, request.Id.Count);
                string batchSql = BuildBatchUpdateSql(request, i, endIndex);

                try
                {
                    int rowsAffected = bHelper.NonQuery(batchSql);
                    totalRowsAffected += rowsAffected;
                }
                catch (System.Exception ex)
                {
                    apiResult.Code = ApiEnum.修改失败;
                    apiResult.Msg = $"报损信息更新失败：{ex.Message}";
                    return apiResult;
                }
            }

            apiResult.Code = totalRowsAffected > 0 ? ApiEnum.修改成功 : ApiEnum.修改失败;
            apiResult.Msg = totalRowsAffected > 0 ? "报损信息更新成功" : "未找到要更新的报损记录";

            return apiResult;
        }

        private string BuildBatchUpdateSql(ReportlossesUpdateModelCommand request, int startIndex, int endIndex)
        {
            string sqlTemplate = @"
            UPDATE ReportlossesModel
            SET Thetypeoflossreport = '{0}',
                Associatetheordernumber = '{1}',
                Makeasingle = '{2}',
                Thetimewhentheorderwasmade = {3},
                Remark = '{4}',
                Productname = '{5}',
                Productcode = '{6}',
                Specification = '{7}',
                Batch = '{8}',
                Unitprice = '{9}',
                Reportedlossquantity = '{10}',
                Warehouse = '{11}',
                Thecurrentlocation = '{12}',
                Reviewstatus = {13},
                Reviewers = '{14}',
                Reasonforreview = '{15}',
                Reviewtime = {16},
                IsDelete = {17},
                Lossreportnumber = '{18}'
            WHERE Id = {19};";

            string EscapeSingleQuotes(string input)
            {
                return input?.Replace("'", "''") ?? string.Empty;
            }

            string GetDateTimeValue(DateTime? dateTime)
            {
                return dateTime.HasValue ? $"'{dateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")}'" : "NULL";
            }

            string GetEnumValue(ApiStatus? status)
            {
                return status.HasValue ? ((int)status.Value).ToString() : "NULL";
            }

            string batchSql = "";
            for (int i = startIndex; i < endIndex; i++)
            {
                var id = request.Id[i];
                if (id == null) // 处理单个Id为null的情况（根据业务需求决定处理方式）
                {
                    // 这里可以选择记录日志、跳过无效Id或抛出异常，当前示例选择跳过
                    continue;
                }

                batchSql += string.Format(sqlTemplate,
                    EscapeSingleQuotes(request.Thetypeoflossreports?[i]),
                    EscapeSingleQuotes(request.Associatetheordernumbers?[i]),
                    EscapeSingleQuotes(request.Makeasingles?[i]),
                    GetDateTimeValue(request.ThetimewhentheorderswereMade?[i]),
                    EscapeSingleQuotes(request.Remarks?[i]),
                    EscapeSingleQuotes(request.Productnames?[i]),
                    EscapeSingleQuotes(request.Productcodes?[i]),
                    EscapeSingleQuotes(request.Specifications?[i]),
                    EscapeSingleQuotes(request.Batches?[i]),
                    EscapeSingleQuotes(request.Unitprices?[i]),
                    EscapeSingleQuotes(request.Reportedlossquantities?[i]),
                    EscapeSingleQuotes(request.Warehouses?[i]),
                    EscapeSingleQuotes(request.Thecurrentlocations?[i]),
                    GetEnumValue(request.Reviewstatuses?[i]),
                    EscapeSingleQuotes(request.Reviewers?[i]),
                    EscapeSingleQuotes(request.Reasonforreviews?[i]),
                    GetDateTimeValue(request.Reviewtimes?[i]),
                    request.IsDeletes?[i] ?? 0,
                    EscapeSingleQuotes(request.Lossreportnumbers?[i]),
                    request.Id[i]);
            }

            return batchSql;
        }
    }
}